package sg.edu.nus.iss.cats.dataaccess.hibernate;

import java.util.ArrayList;
import java.util.List;

import sg.edu.nus.iss.cats.dataaccess.UserDAO;
import sg.edu.nus.iss.cats.exception.HibernateAccessLayerException;
import sg.edu.nus.iss.cats.model.Role;
import sg.edu.nus.iss.cats.model.UserRole;


public class UserRoleDAOImpl extends AbstractDao {

	// Now set its level. Normally you do not need to set the
	// level of a logger programmatically. This is usually done
	// in configuration files.

	public UserRoleDAOImpl() {
		super();
	}

	public Role[] findRolesForUser(String userId)
			throws HibernateAccessLayerException {

		try {
			
			UserDAO userDao = new UserDAOImpl();
			Role[] allRoles = userDao.findAllRoles();
			
			List list = super.findByCategory(UserRole.class, HibernateConstants.ur_userId, userId);
			UserRole[] userRoles = new UserRole[list.size()];
			list.toArray(userRoles);
			ArrayList usrRls = new ArrayList(); 
			for (int i = 0; i < allRoles.length; i++) {
				for (int j = 0; j < userRoles.length; j++) {
					
					if (allRoles[i].getRoleId()
							.equals(userRoles[j].getRoleId())) {
						System.out.println(" all"+allRoles[i].getRoleId()+ " user "+userRoles[j].getRoleId() +  " "+ allRoles[i].getName() + allRoles[i].getDescription());
						usrRls.add(allRoles[i]); 
					}
				}
			}
			Role[] results = new Role[usrRls.size()];
			usrRls.toArray(results);
			for (int i=0; i < results.length; i++)
			{
				System.out.println(" results " + results[i].getRoleId() + results[i].getName() + results[i].getDescription() );
			}
			return results;

		} catch (Throwable t) {

			throw new HibernateAccessLayerException(t.toString());

		}

	}

	public Role[] updateRolesForUser(String userId, Role[] roles)
			throws HibernateAccessLayerException {
		try {
			UserRole[] userRoles = null;
			for (int i = 0; i < roles.length; i++) {
				userRoles[i].setRoleId(roles[i].getRoleId());
				userRoles[i].setUserId(userId);
				super.saveOrUpdate(userRoles[i]);
			}
			return null;
		} catch (Throwable t) {
			throw new HibernateAccessLayerException(t.toString());
		}
	}

}